package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.ExportExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单相关需求
 * @author ChuMingYu
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 支付，生成订单
     * @author ChuMingYu
     */
    @PostMapping("/submit")
    public R submitOrders(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("清空购物车成功");
    }

    /**
     * 分页查询订单
     * @author ChuMingYu
     */
    @GetMapping("/userPage")
    public R selectOrderByPage(Integer page,Integer pageSize){
        IPage<Orders> pageInfo = new Page<>(page,pageSize);
        orderService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();

        List<OrdersDto> collect = records.stream().map((orders)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);

            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getId,ordersDto.getNumber());
            List<OrderDetail> list = orderDetailService.list(qw);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("total",total);
        map.put("records",collect);

        return R.success(map);
    }

    /**
     * 订单明细接口
     * @author ChuMingYu
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Long number,
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date beginTime,
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date endTime){
        log.info("beginTime:{}",beginTime);
        log.info("endTime:{}",endTime);
        //页面构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        //查询所有orders表信息
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //number
        if (number != null){
            queryWrapper.like(Orders::getNumber, number);
        }
        //查询beginTime 大于等于这个时间
        if (beginTime != null){
            queryWrapper.ge(Orders::getOrderTime, beginTime);
        }
        //查询endTime 小于等于这个时间
        if (endTime != null){
            queryWrapper.le(Orders::getOrderTime, endTime);
        }
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, queryWrapper);
        Map map = new HashMap();
        long total = pageInfo.getTotal();
        List<Orders> records = pageInfo.getRecords();
        records.stream().map((item)->{
            item.setUserName(item.getConsignee());
            return item;
        }).collect(Collectors.toList());
        map.put("total",total);
        map.put("records",records);

        return R.success(map);

    }

    /**
     * 导出
     * @author ChuMingYu
     */
    @GetMapping("/export")
    @ResponseBody
    public R export(HttpServletRequest request, HttpServletResponse response){
        //查询数据库中需要导出的数据
        List<Orders> list = orderService.list();
        //创建excel表头
        List<String> column = new ArrayList<>();
        column.add("订单号");
        column.add("订单状态");
        column.add("用户");
        column.add("手机号");
        column.add("地址");
        column.add("下单时间");
        column.add("实收金额");

        //表头对应的数据
        List<Map<String,Object>> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new HashMap();
            Orders orders = list.get(i);
            map.put("订单号",orders.getNumber());
            map.put("订单状态",orders.getStatus());
            map.put("用户",orders.getConsignee());
            map.put("手机号",orders.getPhone());
            map.put("地址",orders.getAddress());
            map.put("下单时间",orders.getOrderTime());
            map.put("实收金额",orders.getAmount());
            data.add(map);
        }

        //调用工具类
        ExportExcel.exportExcel("订单明细",column,data,request,response);

        return R.success("导出成功");
    }

}
